'use strict';
const requireEx =require('yi-require');
module.exports = requireEx('yi-restful').c('bgm',[]);
const ObjectId = require('mongodb').ObjectID;

const middleware =  (req, res, next) =>{
    let authInfo =  req.context||req.context.authInfo ;
    if(!req.context || !req.context.authInfo){
        return res.err.unauthorized();
    }
    authInfo = authInfo.authInfo;

    req.body.userId = new ObjectId(authInfo._id);

    let filter={userId:req.body.userId};
    if(req.body.followedUserId){
        filter["followedUserId"]=req.body.followedUserId;
    }else if(req.body.followedMallId){
        filter["followedMallId"]=req.body.followedMallId;
    }else if(req.body.followedStoreId){
        filter["followedStoreId"]=req.body.followedStoreId;
    }else {
        return res.reply({code:60001,message:"没有关注对象！"});
    }
    req.mongo.collection('fans').find(filter).limit(1).next((e,fans)=>{
        if(!fans){
            req.body.isFollow=1;
            req.mongo.collection('fans').insert(req.body,(err,r0)=>{
                res.reply({code:0,message:"新增关注成功"});
                //可以在next中增加相关的事件
            });
        }else{
            if(fans.isFollow){
                fans.isFollow=0;
            }else{
                fans.isFollow=1;
            }
            req.mongo.collection('fans').updateOne(filter,{$set:{isFollow:fans.isFollow}},(err,r0)=>{
                if(fans.isFollow){
                    res.reply({code:0,message:"关注成功"})
                }else{
                    res.reply({code:0,message:"取消关注成功"})
                }
            });
        }
    });
};

const handler =  (req, res, next) =>{
//暂不处理
};

module.exports = {
    open:false,
    description:'(取消)关注用户/商场/店铺',
    middleware:middleware,
    handler: requireEx('yi-restful').c('fans',[])
};
